package com.yk.system.service.readImpl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yk.api.system.dto.GatewayDTO;
import com.yk.common.core.constant.CacheConstants;
import com.yk.common.core.domain.Result;
import com.yk.common.excel.core.CheckService;
import com.yk.common.redis.service.RedisService;
import com.yk.system.convert.GatewayConvert;
import com.yk.system.entity.Gateway;
import com.yk.system.service.GatewayService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lmx
 * @date 2023/12/28 10:20
 */
@Service
@RequiredArgsConstructor
public class GateWayReadImpl implements CheckService<Gateway> {

    private final GatewayService gatewayService;
    private final GatewayConvert gatewayConvert;
    private final RedisService redisService;

    @Override
    public Result<Gateway> check(Gateway gateway) {
        try{
            if (StrUtil.isEmpty(gateway.getName())){
                return Result.fail("网关名称不能为空");
            }
            if (StrUtil.isEmpty(gateway.getNumber())){
                return Result.fail("网关编号不能为空");
            }
            if (StrUtil.isEmpty(gateway.getTopic())){
                return Result.fail("网关主题不能为空");
            }
            // 后缀必须是/data
            String regex = ".*/data$";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(gateway.getTopic());
            if (!matcher.find()) {
                return Result.fail("网关主题必须以/data结尾");
            }

            String number = gateway.getNumber();
            LambdaQueryWrapper<Gateway> lambda = new LambdaQueryWrapper<>();
            lambda.eq(Gateway::getNumber, number);
            lambda.or();
            lambda.eq(Gateway::getTopic, gateway.getTopic());
            long count = gatewayService.count(lambda);
            if (count > 0L) {
                return Result.fail("网关已存在");
            }
            Long gatewayId = IdWorker.getId();
            gateway.setId(gatewayId);
            gatewayService.save(gateway);
            GatewayDTO dto = gatewayConvert.entity2Dto(gateway);
            dto.setTopic(dto.getTopic());
            redisService.setCacheObject(CacheConstants.GATEWAY_KEY + dto.getTopic(), dto);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}
